//
//  CZPhotoBrowserModalAnimation.swift
//  GZWeibo007
//
//  Created by Apple on 16/1/2.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

class CZPhotoBrowserModalAnimation: NSObject, UIViewControllerAnimatedTransitioning {

    /// 返回动画时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.25
    }
    
    /// 实现modal的动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 获取modal出来的控制器
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! CZPhotoBrowserController
        
        // 获取到modal出来的控制器view
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        
        // 添加到容器视图
        transitionContext.containerView()?.addSubview(toView)
        
        // 将过渡视图添加到容器视图
        let tempImageView = toVC.modalTempImageView()
        
        // TODO:测试,添加到window
//        UIApplication.sharedApplication().keyWindow?.addSubview(tempImageView)
        // 将过渡视图添加到容器视图里面
        transitionContext.containerView()?.addSubview(tempImageView)
        
        toView.alpha = 0
        
        // 需要先隐藏collectionView
        toVC.collectionView.hidden = true
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            // 淡入
            toView.alpha = 1
            
            // 让过渡视图缩放到目标位置
            tempImageView.frame = toVC.modalTargetRect()
            }) { (_) -> Void in
                // 移除过渡视图
                tempImageView.removeFromSuperview()
                
                // 显示collectionView
                toVC.collectionView.hidden = false
                
                transitionContext.completeTransition(true)
        }
        
    }
}
